from datetime import datetime
from flask import Blueprint, request, current_app, g
from util.permission import permission_required
from util.result import Result
from models import db, User, Role  # 确保导入Role模型
from werkzeug.security import check_password_hash, generate_password_hash

# 创建用户管理的蓝图
api_bp = Blueprint('user', __name__)


# 1. 修改用户信息接口
@api_bp.route('/user', methods=['PUT'])
def update_user():
    try:
        data = request.get_json()
        if not data:
            return Result.error("请输入更新信息")

        # 获取当前用户id
        user_id = g.current_user.get('id')
        # 查询指定ID的用户
        user = User.query.get(user_id)
        if not user:
            return Result.error("未找到当前用户")

        # 更新基本用户信息
        if 'name' in data:
            user.name = data['name']
        if 'gender' in data:
            user.gender = data['gender']
        if 'age' in data:
            user.age = data['age']
        if 'phone' in data:
            user.phone = data['phone']
        if 'email' in data:
            user.email = data['email']
        if 'avatar' in data:
            user.avatar = data['avatar']

        # 更新用户信息最后修改时间
        user.updated_at = datetime.now()

        db.session.commit()

        # 获取角色权限
        role = Role.query.get(user.role_id) if user.role_id else None
        # 收集角色权限列表
        permissions = [perm.name for perm in role.permissions] if role else []

        # 构建返回的最新用户数据
        user_data = {
            "id": user.id,
            "username": user.username,
            "name": user.name,
            "gender": user.gender,
            "age": user.age,
            "phone": user.phone,
            "email": user.email,
            "avatar": user.avatar,
            "role_name": role.name,
            'permissions': permissions,
        }

        return Result.success("用户信息更新成功", data=user_data)

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"更新用户信息异常: {str(e)}")
        return Result.error("更新用户信息失败，请稍后重试")


# 2. 修改用户密码接口
@api_bp.route('/user/password', methods=['PUT'])
def change_password():
    try:
        data = request.get_json()
        if not data:
            return Result.error("请输入修改信息")

        # 获取当前用户id
        user_id = g.current_user.get('id')
        # 查询指定ID的用户
        user = User.query.get(user_id)
        if not user:
            return Result.error("未找到当前用户")

        # 处理密码更新
        if 'old_password' in data and 'new_password' in data:
            # 验证原密码是否正确
            if not check_password_hash(user.password_hash, data['old_password']):
                return Result.error("原密码错误")

            # 验证新密码长度
            if len(data['new_password']) < 6:
                return Result.error("新密码长度不能少于6位")

            # 更新密码
            user.password_hash = generate_password_hash(data['new_password'])

        # 更新用户信息最后修改时间
        user.updated_at = datetime.now()

        db.session.commit()

        return Result.success("密码修改成功")

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"更新用户信息异常: {str(e)}")
        return Result.error("更新用户信息失败，请稍后重试")


# 3. 分页查询用户接口（需要user:read权限）
@api_bp.route('/user', methods=['GET'])
@permission_required('user:read')
def search_user():
    try:
        # 1. 获取分页参数（默认第1页，每页10条）
        page = request.args.get('page', type=int)  # 当前页码
        size = request.args.get('size', type=int)  # 每页条数
        # 页码和条数合法性校验
        if page < 1:
            page = 1
        if size < 1 or size > 100:  # 限制最大每页100条，避免性能问题
            size = 10

        # 2. 获取筛选参数
        kw = request.args.get('kw').strip()  # 名称模糊筛选
        status = request.args.get('status')
        begin = request.args.get('begin', type=str)
        end = request.args.get('end', type=str)
        # 3. 构建查询条件
        query = User.query
        if kw:
            query = query.filter(
                (User.name.like(f"%{kw}%") | User.phone.like(f"%{kw}%")) | (User.username.like(f"%{kw}%")))

        if status and status != 'all':
            query = query.filter(User.status == status)

        # 时间范围筛选（begin 和 end 为时间戳）
        if begin:
            begin = datetime.strptime(begin, '%Y-%m-%d')
            query = query.filter(User.created_at >= begin)

        if end:
            end = datetime.strptime(end, '%Y-%m-%d')
            query = query.filter(User.created_at <= end)

        # 4. 构建排序条件（默认按创建时间倒序）
        query = query.order_by(User.created_at.desc())

        # 5. 执行分页查询（SQLAlchemy内置分页方法）
        paginated_result = query.paginate(page=page, per_page=size, error_out=False)
        # 获取当前页数据
        users = paginated_result.items

        # 6. 格式化返回数据
        result_list = [{
            "id": user.id,
            "username": user.username,
            "name": user.name,
            "gender": user.gender,
            "age": user.age,
            "phone": user.phone,
            "email": user.email,
            "avatar": user.avatar,
            "role_id": user.role_id,
            "status": user.status,
            "created_at": user.created_at.strftime("%Y-%m-%d %H:%M:%S"),
            "updated_at": user.updated_at.strftime("%Y-%m-%d %H:%M:%S")
        } for user in users]

        # 7. 构建分页响应体（包含分页元信息，方便前端渲染分页组件）
        page_data = {
            "total": paginated_result.total,  # 总记录数
            "page": page,  # 当前页码
            "size": size,  # 每页条数
            "list": result_list  # 当前页数据列表
        }

        return Result.success("分页查询成功", data=page_data)

    except Exception as e:
        current_app.logger.error(f"分类分页查询异常: {str(e)}")
        return Result.error("分页查询分类失败，请稍后重试")


# 4. 修改用户账号状态接口（需要user:update权限）
@api_bp.route('/user/status', methods=['PUT'])
@permission_required('user:update')
def update_user_status():
    try:
        data = request.get_json()
        if not data:
            return Result.error("请输入更新信息")

        # 获取用户id
        user_id = data['id']
        # 查询指定ID的用户
        user = User.query.get(user_id)
        if not user:
            return Result.error("未找到当前用户")

        # 更新用户状态
        if 'status' in data:
            user.status = data['status']

        # 更新用户信息最后修改时间
        user.updated_at = datetime.now()

        db.session.commit()

        return Result.success("用户账号状态更新成功")

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"更新用户账号状态异常: {str(e)}")
        return Result.error("更新用户账号状态失败，请稍后重试")

# 5. 新增用户接口（需要user:create权限）
@api_bp.route('/user', methods=['POST'])
@permission_required('user:create')
def create_user():
    try:
        data = request.get_json()
        if not data:
            return Result.error("请输入用户信息")

        required_fields = ['username', 'password']
        for field in required_fields:
            if field not in data or not data[field]:
                return Result.error(f"{field} 是必填项")

        # 1. 检查用户名是否已存在
        if User.query.filter_by(username=data['username']).first():
            return Result.error("用户名已存在")


        # 2. 创建用户并关联管理员角色
        user = User(
            username=data['username'],
            role_id=data['role_id'],
            status=1,  # 默认设置为正常状态（1-正常，0-禁用）
            created_at=datetime.now(),
        )
        user.set_password(data['password'])  # 密码加密存储

        # 3. 提交数据库
        db.session.add(user)
        db.session.commit()

        # 4. 返回成功响应
        return Result.success("新增用户成功")

    except Exception as e:
        db.session.rollback()  # 异常时回滚事务，避免数据脏写
        current_app.logger.error(f"新增用户成功异常: {str(e)}")  # 记录错误日志，便于排查
        return Result.error(f"新增用户成功失败: {str(e)}")


# 6. 注销用户账号接口（需要user:delete权限）
@api_bp.route('/user/<int:user_id>', methods=['DELETE'])
@permission_required('user:delete')
def delete_user(user_id):
    try:
        user = User.query.get(user_id)
        if not user:
            return Result.error("账号不存在")

        db.session.delete(user)
        db.session.commit()

        return Result.success("账号注销成功")

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"账号注销异常: {str(e)}")
        return Result.error("账号注销失败，请稍后重试")